'use strict';

import {
  appConst,
  appData,
  appMain,
  appSession,
  appUtils,
} from './instances';

/**
 * @class AppData 持久化数据
 */
class AppData {
  /**
   * @method constructor
   */
  constructor() {
    // this._appMain = appMain;
    this._loaded = false;
    this._data = {
      'record_count': 0,
      'record_first': '',
      'record_last': '',
      'records': {}
    };
  }

  // 记录统计
  summary() {
    return appConst.tpls.recordSummary.format({
      'count': Object.keys(this._data.records).length
    });
  }

  // 时间段记录统计
  summaryRange(day, tr) {
    let count = 0;
    let items = [];
    let itemNow = this._data.record_first;
    while (itemNow !== undefined && itemNow.length > 0) {
      if (this._data.records.hasOwnProperty(itemNow)) {
        let record = this._data.records[itemNow];
        if ((new Date(record.create_time)).inRange(tr)) {
          count++;
          items.push(itemNow);
        }
        itemNow = record.next;
      } else {
        itemNow = '';
      }
    }
    appSession.set('explore_records', items);
    return appConst.tpls.recordSummaryDay.format({
      'day': day,
      'ts': tr[0].format('YYYY年MM月DD日'),
      'te': tr[1].format('YYYY年MM月DD日'),
      'count': count
    });
  }

  exploreRange(day) {
    let ttsStr = '';
    console.debug('[RecordExploreSelect]', JSON.stringify(day));
    if (day === '总共' || day === '一共' || day === '全部') {
      ttsStr = appData.summary();
      appSession.set('explore_time_range', []);
    } else {
      let now = new Date();
      let timeRange = now.parseRange(day);
      ttsStr = appData.summaryRange(day, timeRange);
      appSession.set('explore_time_range', timeRange);
    }
    return ttsStr;
  }

  // 浏览记录
  // 上一条、下一条、上三条、下三条等
  exploreRecord(value) {
    let self = this;
    let record = null;
    let explore_time_range = appSession.get('explore_time_range');
    let explore_current = appSession.get('explore_current');
    let explore_offset = appSession.get('explore_offset'); // 起始：1
    let records = appSession.get('explore_records'); // ids
    let explore_type = 'range'; // range|all
    // session 变量检查及初始化
    if (explore_time_range === null || typeof (explore_time_range) !== 'object' ||
      explore_time_range.length !== 2) {
      explore_type = 'all';
    }
    if (typeof (explore_offset) !== 'number') {
      explore_offset = 1;
    }
    let explore_now = explore_current;
    let hitOffset = (callback) => { // 移动偏移标记
      let res = callback();
      if (value > 0) value -= 1;
      if (value < 0) value += 1;
      return res;
    }
    switch (explore_type) {
      case 'range':
        if (!records) { // 范围内无记录
          records = [];
        }
        explore_offset += value;
        if (explore_offset <= 0) {
          explore_offset = 1;
        }
        if (explore_offset > records.length && records.length > 0) {
          explore_offset = records.length;
        }
        explore_now = records[explore_offset - 1];
        appSession.set('explore_current', explore_now);
        appSession.set('explore_offset', explore_offset);
        break;
      default:
        if (!explore_now ||
          (!this._data.records.hasOwnProperty(explore_now))) {
          explore_now = this._data.record_first;
        }
        if (this._data.records.hasOwnProperty(explore_now)) {
          while (value !== 0) {
            explore_now = hitOffset(() => {
              if (self._data.records.hasOwnProperty(explore_now)) {
                if (value > 0) {
                  return self._data.records[explore_now].next;
                } else {
                  return self._data.records[explore_now].prev;
                }
              }
            });
          }
          appSession.set('explore_current', explore_now);
        }
        break;
    }
    record = this._data.records[explore_now];
    appSession.set('record_previous', record);

    console.debug('[exploreRecord]', JSON.stringify(this._data.records), JSON.stringify(record));
    return record;
  }

  // 添加记录
  addRecordNormal(str) {
    console.debug('[addRecordNormal]');
    let recordData = new Date();
    let curUuid = appUtils.genUuid();
    let record = {
      id: curUuid, // 条目ID
      prev: '', // 上一条
      next: '', // 下一条
      title: '', // 标题
      category: 'Normal', // 分类
      tags: [], // 标签
      content: str, // 内容
      lal: null, // 坐标
      address: null, // 位置
      create_time: recordData,
      update_time: recordData,
      delete_time: null,
      history: [] // 历史记录
    };
    console.debug('[addRecordNormal]', this._data.record_last);
    if (this._data.record_first === '') {
      this._data.record_first = record.id;
      this._data.record_last = record.id;
    } else if (this._data.record_last !== undefined && this._data.record_last !== '') {
      this._data.records[this._data.record_last].next = record.id;
      record.prev = this._data.record_last;
      this._data.record_last = record.id;
    }
    this._data.records[curUuid] = record;
    return record;
  }

  // 更新记录记录
  setRecordNormal(record) {
    // 链接表形式
    this._data.records[record.id] = record;
    return record;
  }

  // 获取记录
  getRecord(id) {
    // 链接表形式
    if (this._data.records.hasOwnProperty(id)) {
      return this._data.records[id];
    }
    return null;
  }

  // 删除记录
  delRecord(id) {
    // 链接表形式
    let record = null;
    if (this._data.records.hasOwnProperty(id)) {
      this._data.records[id].delete_time = new Date();
      record = this._data.records[id];

      if (record.prev === '') {
        this._data.record_first = record.next;
      } else {
        this._data.records[record.prev].next = record.next;
      }

      if (record.next === '') {
        this._data.record_last = record.prev;
      } else {
        this._data.records[record.next].prev = record.prev;
      }
    }
    return record;
  }

  // 恢复数据到全局变量
  recoverData(json) {
    this._data = json;
  }

  // 从数据库恢复保存的数据
  reload(callback) {
    let self = this;
    let err = null;
    if (!self._loaded) {
      self._loaded = true;
      let key = self._appMain.getUserID() + '_data';
      Rokid.dbServer.get(key, (error, result) => {
        if (error) {
          console.debug('[DBReloadError]', error);
          err = error;
        } else {
          if (result.length > 2 || result != '未查询到相关数据') {
            try {
              self.recoverData(JSON.parse(result));
            } catch (e) {
              console.debug('[DEBUG]', e);
              err = e;
            }
            console.debug('[DBReloadResult]', JSON.stringify({
              "key": key,
              "size": Object.keys(self._data.records).length
            }));
          }
        }
        callback(err);
      });
    }
  }

  // 提交数据到数据库
  submit(callback) {
    let key = appMain.getUserID() + '_data';
    let data = JSON.stringify(this._data);
    let err = null;
    console.debug('[DBSubmit]', JSON.stringify({
      "key": key,
      "size": this._data.length
    }));
    Rokid.dbServer.set(key, data, (error, result) => {
      if (error) {
        err = error;
        console.debug('[DBSubmitError]', err);
      }
      callback(err);
    });
  }

  // 清空记录
  clearUpItems() {
    this._data = {
      'record_count': 0,
      'record_first': '',
      'record_last': '',
      'records': {}
    };
  }
}

export default AppData;
